<template>
  <div class="card-full">
    <div class="search-box">
      <el-form ref="ruleSearchFormRef" class="search-form" :model="searchForm" inline>
        <el-form-item label="" prop="keyword">
          <el-input v-model="searchForm.keyword" placeholder="输入关键词搜索" />
        </el-form-item>
      </el-form>
      <el-button class="ml-4" type="primary" @click="getList">查询</el-button>
      <el-button plain @click="(ruleSearchFormRef.resetFields(), getList())">重置</el-button>
    </div>
    <div class="mb-2">
      <el-button v-permission="'role:add'" type="primary" @click="isShow = true">新增</el-button>
    </div>
    <div class="table-box">
      <el-table :data="tableData" border header-align="center">
        <el-table-column prop="role_name" label="角色名称" min-width="120" align="center" />
        <el-table-column prop="role_code" label="角色编码" min-width="120" align="center" />
        <el-table-column prop="role_desc" label="角色描述" min-width="120" align="center" />
        <el-table-column prop="status" label="角色状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="primary">启用</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="120" align="center" />
        <el-table-column fixed="right" label="操作" min-width="120" align="center">
          <template #default="scope">
            <el-button v-permission="'role:update'" link type="primary" size="small" @click="handleClick(scope.row)"
              >编辑</el-button
            >
            <el-button v-permission="'role:delete'" link type="primary" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-drawer v-model="isShow" @close="resetForm">
      <template #header>
        <div class="font-bold">{{ form.id ? "编辑" : "新增" }}角色</div>
      </template>
      <template #default>
        <div>
          <el-form ref="ruleFormRef" label-position="right" label-width="auto" :model="form" :rules="rules">
            <el-form-item label="角色名称" prop="role_name">
              <el-input v-model="form.role_name" />
            </el-form-item>
            <el-form-item label="角色编码" prop="role_code">
              <el-input v-model="form.role_code" />
            </el-form-item>
            <el-form-item label="角色描述" prop="role_desc">
              <el-input v-model="form.role_desc" type="textarea" />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
            </el-form-item>
            <el-form-item label="角色权限" prop="menu_ids">
              <el-tree ref="treeRef" :data="roleList" show-checkbox node-key="id" :default-checked-keys="form.menu_ids">
                <template #default="{ data }">
                  <div class="custom-tree-node">
                    <span>{{ data.meta.title }}</span>
                  </div>
                </template>
              </el-tree>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="confirmClick(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ElForm, ElMessage } from "element-plus";
import * as Api from "@/api/modules/role";
import { getMenuList } from "@/api/modules/menu";
import type { FormInstance, FormRules } from "element-plus";

const searchForm = ref({ keyword: "" });
const ruleSearchFormRef = ref<FormInstance>();
const tableData = ref([]);
const getList = async () => {
  const { data } = await Api.getRoleList({
    ...searchForm.value,
    page: currentPage.value,
    page_size: pageSize.value
  });

  tableData.value = data.list;
  total.value = data.total;
};
const roleList = ref([]);
const getroleList = () => {
  getMenuList().then(res => {
    roleList.value = res.data.list;
  });
};

const isShow = ref(false);
const form = ref<Api.Role>({
  menu_ids: [],
  status: 1
});
const ruleFormRef = ref<FormInstance>();
const treeRef = ref();
const rules = reactive<FormRules<Api.Role>>({
  role_name: { required: true, message: "请输入角色名称", trigger: "blur" },
  role_code: { required: true, message: "请输入角色编码", trigger: "blur" },
  menu_ids: { required: true, message: "请输入角色权限", trigger: "blur" }
});

const confirmClick = async (formEl: FormInstance | undefined) => {
  form.value.menu_ids = treeRef.value.getCheckedKeys();
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (form.value.id) {
        await Api.editRole(form.value).then(res => {
          getList();
          isShow.value = false;
        });
      } else {
        await Api.addRole(form.value).then(res => {
          getList();
          isShow.value = false;
        });
      }
      ElMessage({
        message: form.value.id ? "编辑成功" : "添加成功",
        type: "success"
      });
      resetForm();
    }
  });
};
const handleClick = async row => {
  const { data } = await Api.detailRole(row.id);
  form.value = data;
  isShow.value = true;
};
const handleDelete = (id: number) => {
  Api.delRole({ ids: [id] })
    .then(res => {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      isShow.value = false;
    })
    .catch(err => {
      ElMessage({
        message: err.message,
        type: "success"
      });
    });
};
const resetForm = () => {
  form.value = {
    menu_ids: [],
    status: 1
  };
  isShow.value = false;
};

const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

onMounted(() => {
  getList();
  getroleList();
});
</script>
<style lang="scss" scoped>
:deep(.el-drawer__footer) {
  padding: 15px;
  border-top: 1px solid var(--color-border-2);
}
:deep(.el-drawer__header) {
  margin-bottom: 0;
}
</style>
